<?php
class ControllerAccountResetTelephone extends Controller {
	private $error = array();
	private $code = '';

	public function index() {
		$this->load->language('account/reset_telephone');

		$this->document->setTitle($this->language->get('heading_title'));

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->load->model('account/customer');

			$this->session->data['success'] = $this->language->get('text_success');

			// Add to activity log
			if ($this->config->get('config_customer_activity')) {
				$this->load->model('account/activity');

				$activity_data = array(
					'customer_id' => $this->customer->getId(),
					'name'        => $this->customer->getFirstName()
				);

				$this->model_account_activity->addActivity('password_pre', $activity_data);
			}

			$this->response->redirect($this->url->link('account/reset', '&code=' . $this->code, true));
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_account'),
			'href' => $this->url->link('account/account', '', true)
		);

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_code'] = $this->language->get('text_code');

		$data['entry_code'] = $this->language->get('entry_code');

		$data['button_continue'] = $this->language->get('button_continue');
		$data['button_back'] = $this->language->get('button_back');

		if (isset($this->error['code'])) {
			$data['error_code'] = $this->error['code'];
		} else {
			$data['error_code'] = '';
		}

		$data['action'] = $this->url->link('account/reset_telephone', 'telephone=' . $this->request->get['telephone'], true);

		if (isset($this->request->post['code'])) {
			$data['code'] = $this->request->post['code'];
		} else {
			$data['code'] = '';
		}

		$data['back'] = $this->url->link('account/forgotten', '', true);

		$data['column_left'] = $this->load->controller('common/column_left');
		$data['column_right'] = $this->load->controller('common/column_right');
		$data['content_top'] = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer'] = $this->load->controller('common/footer');
		$data['header'] = $this->load->controller('common/header');

		$this->response->setOutput($this->load->view('account/reset_telephone', $data));
	}

	protected function validate() {
		$this->load->model('account/customer');
		$customer_info = $this->model_account_customer->getCustomerByTelephone($this->request->get['telephone']);

		if (!$customer_info || substr($customer_info['code'], -6) != $this->request->post['code']) {
			$this->error['code'] = $this->language->get('error_code');
		}
		$this->code = $customer_info['code'];

		return !$this->error;
	}
}